import { Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { MagicEntity } from '../entity/magic';
import { MagicCateEntity } from '../entity/magicCate';
/**
 * 描述
 */
@Provide()
export class MagicService extends BaseService {
  @InjectEntityModel(MagicEntity)
  magicEntity: Repository<MagicEntity>;

  @InjectEntityModel(MagicCateEntity)
  magicCateEntity: Repository<MagicCateEntity>;

  async getPageInfoById(params: any) {
    const data = await this.magicEntity.findOne({
      id: params.id,
      status: 1,
    });
    if (!data) {
      throw new CoolCommException(
        `页面加载错误~id:[${params.id}]-source:[${params.source}]`
      );
    }
    return data;
  }
  /**
   * 获取活动页面
   * @param params
   * @returns
   */
  async getPageInfoByKey(params: any) {
    const data = await this.magicEntity
      .createQueryBuilder()
      .select()
      .where('magic_key=:magicKey', { magicKey: params.key })
      .andWhere('status = 1')
      .orderBy(`field(source,'default','${params.source}')`, 'DESC')
      .addOrderBy('sort', 'DESC')
      .limit(1)
      .getOne();
    if (!data) {
      throw new CoolCommException(
        `页面加载错误~[${params.magicKey}-${params.source}]`
      );
    }
    return data;
  }
  /**
   * 获取活动页面
   * @param params
   * @returns
   */
  async getCateList(params: any) {
    const data = await this.magicCateEntity
      .createQueryBuilder()
      .select()
      .where('status = 1')
      .orderBy(`field(source,'default','${params.source}')`, 'DESC')
      .addOrderBy('sort', 'ASC')
      .getMany();
    if (!data) {
      throw new CoolCommException(`分类加载错误~[${params.source}]`);
    }
    return data;
  }
}
